package offer;

import utils.Node;

/**
 * <p>
 * 剑指 Offer 36. 二叉搜索树与双向链表
 * </p>
 *
 * @author xiaozuolin
 * @date 2021/9/24 10:11
 */
public class Offer36 {
    Node pre;
    Node head;

    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return null;
        }
        dfs(root);
        head.left = pre;
        pre.right = head;
        return head;
    }

    public void dfs(Node root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        if (pre != null) {
            pre.right = root;
        } else {
            head = root;
        }
        root.left = pre;
        pre = root;
        dfs(root.right);
    }
}
